package com.gml.design.other.singleton;

/**
 * @ClassName : Singleton04
 * @Description : 懒汉式单例
 *  synchronized用来保证线程安全性，加锁
 *  缺点：加锁以后效率降低，每次执行都需要去获取锁
 * @Author : gml
 * @Date: 2021-04-01 14:13
 */
public class Singleton04 {

    private static Singleton04 INSTANCE;

    private Singleton04(){}

    public static synchronized Singleton04 getInstance() throws InterruptedException {
        if (null == INSTANCE){
            Thread.sleep(100);
            INSTANCE = new Singleton04();
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++){
            new Thread(() -> {
                try {
                    System.out.println(Singleton04.getInstance().hashCode());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

}
